///增加更多的文档
// 为线程池增加测试
// 尽可能移除 unwrap，替换为错误处理
// 使用线程池完成其它类型的工作，而不仅仅是本章的 Web 服务器
// 在 crates.io 上找到一个线程池实现，然后使用该包实现一个类似的 Web 服务器

use std::{sync::mpsc, thread};
use std::sync::{Arc, Mutex};

type Job = Box<dyn FnOnce() + Send + 'static>;

pub struct ThreadPool {
    workers: Vec<Worker>,
    // sender: mpsc::Sender<Job>,
    sender: Option<mpsc::Sender<Job>>,
}

impl ThreadPool {
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);

        let (sender, receiver) = mpsc::channel();

        let receiver = Arc::new(Mutex::new(receiver));

        let mut workers = Vec::with_capacity(size);

        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool {
            workers,
            // sender
            sender: Some(sender),
        }
    }

    pub fn execute<F>(&self, f: F)
        where
            F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);

        //self.sender.send(job).unwrap();
        self.sender.as_ref().unwrap().send(job).unwrap();
    }
}

struct Worker {
    id: usize,
    //thread: thread::JoinHandle<()>,//
    thread: Option<thread::JoinHandle<()>>,
}

impl Worker {
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        // 尚未实现..
        let thread = thread::spawn(move || loop {
            // 接收到一个任务
            // let message = receiver.lock().unwrap().recv();
            //
            // match message {
            //     Ok(job) => {
            //         println!("Worker {id} got a job; executing.");
            //         job();
            //     }
            //     Err(_) => {
            //         println!("Worker {id} disconnected; shutting down.");
            //         // break;
            //     }
            // }

            let job = receiver.lock().unwrap().recv();
            println!("Worker {id} got a job; executing.");
            job();
        });
        // 每个 `Worker` 都拥有自己的唯一 id
        Worker {
            id,
            thread: Some(thread),
        }
    }
}

/// graceful shutdown
impl Drop for ThreadPool {
    fn drop(&mut self) {
        drop(self.sender.take());

        for woker in &mut self.workers {
            println!("Worker {} shutting down.", woker.id);
            //woker.thread.join().unwrap();
            if let Some(thread) = woker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}



